import '../../common/common.less';
import './index.less';
import '../../common/common.js';
import $tool from '../../common/tool.js';
import $store from '../../common/store.js';
import $ajax from '../../common/ajax.js';

$('#header').load('./zqxx_header.html');
$('#footer').load('./footer.html');

$(function () {
  //加载语言包
  $tool.loadProperties(res => {
    let html = [
      'string_title', 'string_title_tip', 'string_role_platform',
      'string_nav_user_title', 'string_nav_role_title', 'string_nav_recharge_type_title', 'string_nav_recharge_title',
      'string_bind_gg_user', 'string_bind_fb_user', 'string_bind', 'string_no_bind',
      'string_role_serverId', 'string_role_name', 'string_role_id', 'string_role_level',
      'string_recharge_TWD', 'string_recharge_goods'
    ]
    html.forEach(item => {
      $("." + item).html($.i18n.prop(item))
    })
  });

  $('.choice').click(function () {
    $(".choice").removeClass("active");
    $(this).addClass("active");
  });

  var username = localStorage.getItem('username');
  var userId = localStorage.getItem('userId');
  if (username != null && username != undefined && username != '' && userId != null && userId != undefined && userId != '') {
    initAccount(username, userId);
  }

  $("#paltform").change(function () {
    var curPaltform = $('#paltform').val();
    if (username && userId && curPaltform) {
      initUserRole(username, userId, curPaltform);
      initRecharge(curPaltform);
    }
  });

  $("#server").change(function () {
    var curServerid = $('#server').val();
    if (curServerid) {
      getUserRoleInfoByCurServer(curServerid);
    }
  });

  $("#recharge").change(function () {
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    $("#recharge_TWD").val(twd_price);
    $("#recharge_goods").val(goodsId_count);
  });

  $("#finish").click(function () {
    var msg = form_validate();
    var idx = $("ul .active").index();
    if (msg != true && idx !== 2) {
      $tool.showError(msg);
      return;
    }
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    let $el = $tool.showconfim({
      text: '您即将花费Mycard ' + twd_price + '點, 获取' + goodsId_count + '靈玉',
      cancel_text: '取消',
      submit_text: '确定',
      cancelfn: () => {
        $el.fadeOut("fast")
      }, //不写取消事件 则取消按钮隐藏
      submitfn: () => {
        // var evt = document.createEvent("MouseEvents"); 
        // evt.initEvent("click", true, true); 
        // document.getElementById("finish").dispatchEvent(evt); 
        $el.fadeOut("fast")
        getPayUrl();
      },
    })
  });

  $("#next").click(function () {
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    var idx = $("ul .active").index();
    if (idx === 10) {
      let $el = $tool.showconfim({
        text: '您即将花费Mycard ' + twd_price + '點, 获取' + goodsId_count + '靈玉',
        cancel_text: '取消',
        submit_text: '确定',
        cancelfn: () => {
          $el.fadeOut("fast")
        }, //不写取消事件 则取消按钮隐藏
        submitfn: () => {
          // var evt = document.createEvent("MouseEvents"); 
          // evt.initEvent("click", true, true); 
          // document.getElementById("finish").dispatchEvent(evt); 
          $el.fadeOut("fast")
        },
      })
    }
  });

  $("#previous").click(function () {
    $('#recharge_iframe').html('');
  });
});

function initAccount(username, userId) {
  // var username = localStorage.getItem('username');
  // var userId = localStorage.getItem('userId');
  if (username != null && username != undefined && username != '') {
    $('#username').val(username);
  }
  if (userId != null && userId != undefined && userId != '') {
    $('#userId').val(userId);
  }
  var bindFB = JSON.parse(localStorage.getItem('bindFB'));
  var bindGoogle = JSON.parse(localStorage.getItem('bindGoogle'));
  if (bindFB != null && bindFB !== undefined && bindFB.isBind) {
    $('#no_bind_fb').prop('checked', false);
    $('#bind_fb').prop('checked', true);
    $('#facebook_username').val(bindFB.otherAccountName);
  }
  if (bindGoogle != null && bindGoogle !== undefined && bindGoogle.isBind) {
    $('#no_bind_gg').prop('checked', false);
    $('#bind_gg').prop('checked', true);
    $('#google_username').val(bindFB.otherAccountName);
  }
}

function initUserRole(username, userId, curPaltform) {
  localStorage.setItem('serverData', []);
  localStorage.setItem('userRoleData', []);
  var requestRoleData = {
    username: username,
    uid: userId,
    paltform: curPaltform
  };
  $.get('/php/getUserRole.php', requestRoleData, function (response) {
    var res = JSON.parse(response);
    var serverData = [];
    var userRoleMap = new Map();
    if (res.code == 200) {
      var userRoleDatas = res.data;
      for (var i in userRoleDatas) {
        var userRoleData = userRoleDatas[i];
        var server_id = userRoleData.serverId;
        var server_name = userRoleData.serverName;
        serverData.push({
          "server_id": server_id,
          "server_name": server_name
        });
        userRoleMap.set(server_id, userRoleData);
      }
    }
    localStorage.setItem('serverData', JSON.stringify(serverData));

    // var obj= Object.create(null);
    // for (var[k,v] of userRoleMap) {
    //   obj[k] = v;
    // }
    var obj = MapToObj(userRoleMap);
    localStorage.setItem('userRoleData', JSON.stringify(obj));

    // var serverData = JSON.parse(localStorage.getItem('serverData'));
    var serverSelect = document.getElementById("server");
    serverSelect.options.length = 0;
    for (var i = 0;
      (serverData != null && serverData != undefined) && i < serverData.length; i++) {
      //先创建好select里面的option元素
      var option = document.createElement("option");
      //转换DOM对象为JQ对象,好用JQ里面提供的方法 给option的value赋值
      $(option).val(serverData[i].server_id);
      //给option的text赋值,这就是你点开下拉框能够看到的东西
      $(option).text(serverData[i].server_name);
      //获取select 下拉框对象,并将option添加进select
      serverSelect.options.add(option);
    }
    var curServerid = $('#server').val();
    if (curServerid != null && curServerid != undefined && curServerid > 0) {
      getUserRoleInfoByCurServer(curServerid);
    }
  });
}

function initRecharge(curPaltform) {
  // $.get("/php/getProducts.php", {paltform: curPaltform}, function(response) {
  $.get("/php/getProducts.json", {
    paltform: curPaltform
  }, function (response) {
    // var res = JSON.parse(response);
    var res = response;
    var productsData = res.data;
    // localStorage.setItem('productsData', JSON.stringify(productsData));
    // var productsData = JSON.parse(localStorage.getItem('productsData'));
    var rechargeSelect = document.getElementById("recharge");
    rechargeSelect.options.length = 0;
    for (var i = 0;
      (productsData != null && productsData != undefined) && i < productsData.length; i++) {
      //先创建好select里面的option元素
      var option = document.createElement("option");
      //转换DOM对象为JQ对象,好用JQ里面提供的方法 给option的value赋值
      $(option).val(productsData[i].goodsId);
      //给option的text赋值,这就是你点开下拉框能够看到的东西
      $(option).text(productsData[i].product_name);
      $(option).attr("twd_price", productsData[i].twd_price); //自定义属性商品Id
      $(option).attr("goodsId_count", productsData[i].goodsId_count); //自定义属性商品数量
      //获取select 下拉框对象,并将option添加进select
      rechargeSelect.options.add(option);
    }
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    $("#recharge_TWD").val(twd_price);
    $("#recharge_goods").val(goodsId_count);
  });
}

function MapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k, v] of strMap) {
    obj[k] = v;
  }
  return obj;
}

function ObjToMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}

function getUserRoleInfoByCurServer(curServerid) {
  var userRoleData = JSON.parse(localStorage.getItem('userRoleData'));
  if (userRoleData != null && userRoleData != undefined && userRoleData != '{}') {
    var userRoleData_ = ObjToMap(userRoleData);
    var UserRoleInfo = userRoleData_.get(curServerid);
    if (UserRoleInfo != null && UserRoleInfo != undefined && UserRoleInfo != '') {
      $("#role_name").attr("value", UserRoleInfo.roleName);
      $("#role_id").attr("value", UserRoleInfo.roleId);
      $("#role_level").attr("value", UserRoleInfo.roleLevel);
    }
  }
}

function getPayUrl() {
  var username = $('#username').val().trim();
  var userId = $('#userId').val().trim();
  var curFBName = $('#facebook_username').val().trim();
  var curGGName = $('#google_username').val().trim();
  var curPaltform = $('#paltform').val();
  var curServerid = $('#server').val();
  var curServerName = $("#server").find("option:selected").text().trim();
  var curRoleName = $("#role_name").val().trim();
  var curRoleId = $("#role_id").val().trim();
  var curRoleLevel = $("#role_level").val().trim();
  var curRechargeType = $(".choice.active").text().trim();
  var curPrice = $('#recharge').val();
  var curGoodsId = $("#recharge").find("option:selected").text().trim();
  var requestData = {
    userId: userId,
    goodsId: curPrice,
    roleName: curRoleName,
    roleId: curRoleId,
    serverName: curServerName,
    serverId: curServerid,
    paltform: curPaltform
  };
  $.get('/php/getPayUrl.php', requestData, function (response) {
    console.log(response);
    var res = JSON.parse(response);
    if (res.status == true) {
      window.open('http://' + res.data.payUrl, '_self');
      // var ifrm = document.createElement("iframe");
      // var protocol = document.location.protocol;
      // ifrm.setAttribute("src", protocol + '//' + res.data.payUrl);
      // ifrm.style.width = "640px";
      // ifrm.style.height = "480px";
      // ifrm.style.width = "99%";
      // ifrm.style.height = "500px";
      // $('#recharge_iframe').html(ifrm);
    } else {
      $tool.showError('支付地址获取失败');
    }
  });
}

function form_validate() {
  var username = $('#username').val().trim();
  var userId = $('#userId').val().trim();
  var curFBName = $('#facebook_username').val().trim();
  var curGGName = $('#google_username').val().trim();
  var curServerid = $('#server').val();
  var curServerName = $("#server").find("option:selected").text().trim();
  var curRoleName = $("#role_name").val().trim();
  var curRoleId = $("#role_id").val().trim();
  var curRoleLevel = $("#role_level").val().trim();
  var curRechargeType = $(".choice.active").text().trim();
  var curPrice = $('#recharge').val();
  var curGoodsId = $("#recharge").find("option:selected").text().trim();

  if (username == null || username == undefined || username == '') {
    return $.i18n.prop('string_form_nologin_msg');
  }
  if (userId == null || userId == undefined || userId == '') {
    return $.i18n.prop('string_form_nologin_msg');
  }
  if ((curFBName == null || curFBName == undefined || curFBName == '') && (curGGName == null || curGGName == undefined || curGGName == '')) {
    return $.i18n.prop('string_form_user_msg');
  }
  // if(curGGName ==null || curGGName == undefined || curGGName == '') {
  //   return $.i18n.prop('string_form_nologin_msg');
  // }
  if (curServerid == null || curServerid == undefined || curServerid == '') {
    return $.i18n.prop('string_form_server_msg');
  }
  if (curServerName == null || curServerName == undefined || curServerName == '') {
    return $.i18n.prop('string_form_server_msg');
  }
  if (curRoleName == null || curRoleName == undefined || curRoleName == '') {
    return $.i18n.prop('string_form_role_msg');
  }
  if (curRoleId == null || curRoleId == undefined || curRoleId == '') {
    return $.i18n.prop('string_form_role_msg');
  }
  if (curRoleLevel == null || curRoleLevel == undefined || curRoleLevel == '') {
    return $.i18n.prop('string_form_role_msg');
  }
  // if(curRechargeType == null || curRechargeType == undefined || curRechargeType == '' || curRechargeType != 'Mycard') {
  //   return $.i18n.prop('string_form_rechargeType_msg');
  // }
  if (curPrice == null || curPrice == undefined || curPrice == '') {
    return $.i18n.prop('string_form_recharge_msg');
  }
  if (curGoodsId == null || curGoodsId == undefined || curGoodsId == '') {
    return $.i18n.prop('string_form_recharge_msg');
  }
  return true;
}